package org.gabrielnegri.fitparser;

import java.lang.reflect.Type;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;


/**
 * Converter implementation for XMLGregorianCalendar
 * 
 * @author gabriel.negri
 *
 */
public class XMLGregorianCalendarConverter {

	public static class Serializer implements
			JsonSerializer<XMLGregorianCalendar> {

		@Override
		public JsonElement serialize(XMLGregorianCalendar t, Type type,
				JsonSerializationContext jsonSerializationContext) {
			return new JsonPrimitive(t.toXMLFormat());
		}
	}

	public static class Deserializer implements
			JsonDeserializer<XMLGregorianCalendar> {
		public XMLGregorianCalendar deserialize(JsonElement jsonElement,
				Type type, JsonDeserializationContext jsonDeserializationContext) {
			try {
				return DatatypeFactory.newInstance().newXMLGregorianCalendar(
						jsonElement.getAsString());
			} catch (Exception e) {
				return null;
			}
		}
	}
}
